package com.pernix.authen;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.pernix.authen.model.AuthenUser;

public class jdbchelper {
	private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
	private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/security";
	private static final String DB_USER = "root";
	private static final String DB_PASSWORD = "Sa111111";
 
 
	public static AuthenUser Authentication(String userid) throws SQLException {
 
		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;
        
		AuthenUser result=null;
		
		String SQL = "SELECT username,salt,passhash FROM Login where username= ?";
 
		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(SQL);
			preparedStatement.setString(1,userid);
			ResultSet rs=preparedStatement.executeQuery();
            
			while(rs.next()){
			   result = new AuthenUser();
               result.setUsername(rs.getString(1));
               result.setSalt(rs.getString(2));
               result.setPasshash(rs.getString(3));
              
               }
			return result;
 
			//System.out.println("Complete");
 
		} catch (SQLException e) {
 
			System.out.println(e.getMessage());
	
 
		} finally {
 
			if (preparedStatement != null) {
				preparedStatement.close();
			}
 
			if (dbConnection != null) {
				dbConnection.close();
			}
 
		}
		return result;
 
	}
 
	
	
	private static Connection getDBConnection() {
 
		Connection dbConnection = null;
 
		try {
 
			Class.forName(DB_DRIVER);
 
		} catch (ClassNotFoundException e) {
 
			System.out.println(e.getMessage());
 
		}
 
		try {
 
			dbConnection = DriverManager.getConnection(
                              DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;
 
		} catch (SQLException e) {
 
			System.out.println(e.getMessage());
 
		}
 
		return dbConnection;
 
	}
 
	private static java.sql.Timestamp getCurrentTimeStamp() {
 
		java.util.Date today = new java.util.Date();
		return new java.sql.Timestamp(today.getTime());
 
	}
 

}
